package com.dlc.shop.security.api.controller;

import com.dlc.shop.bean.model.Station;
import com.dlc.shop.common.enums.SysTypeEnum;
import com.dlc.shop.common.exception.YamiShopBindException;
import com.dlc.shop.common.response.ServerResponseEntity;
import com.dlc.shop.security.common.bo.UidInfoBO;
import com.dlc.shop.security.common.dto.AuthenticationDTO;
import com.dlc.shop.security.common.manager.PasswordCheckManager;
import com.dlc.shop.security.common.manager.PasswordManager;
import com.dlc.shop.security.common.manager.TokenStore;
import com.dlc.shop.security.common.vo.TokenInfoVO;
import com.dlc.shop.service.StationService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.Objects;

/**
 * @author FrozenWatermelon
 * @date 2020/6/30
 */
@RestController
@Tag(name = "自提点登录")
@AllArgsConstructor
public class StationLoginController {

    private final TokenStore tokenStore;
    private final StationService stationService;
    private final PasswordCheckManager passwordCheckManager;
    private final PasswordManager passwordManager;


    @PostMapping("/stationLogin")
    @Operation(summary = "自提点账号密码(用于前端登录)" , description = "通过账号/手机号/用户名密码登录")
    public ServerResponseEntity<TokenInfoVO> login(
            @Valid @RequestBody AuthenticationDTO authenticationDTO) {

        Station station = stationService.getStationInfoByAccount(authenticationDTO.getUserName());
        // 密码不正确
        if (Objects.isNull(station)){
            // 账号或密码不正确
            throw new YamiShopBindException("yami.user.account.error");
        }
        String decryptPassword = passwordManager.decryptPassword(authenticationDTO.getPassWord());
        // 半小时内密码输入错误十次，已限制登录30分钟
        passwordCheckManager.checkPassword(SysTypeEnum.STATION,authenticationDTO.getUserName(), decryptPassword, station.getPassword());

        if (!Objects.equals(station.getStatus(),1)){
            // 该自提点已关闭，请联系管理员
            throw new YamiShopBindException("yami.shop.station.close");
        }
        UidInfoBO uidInfoBO = new UidInfoBO(SysTypeEnum.STATION, String.valueOf(station.getStationId()), station.getShopId());
        uidInfoBO.setAdmin(0);
        return ServerResponseEntity.success(tokenStore.storeAndGetVo(uidInfoBO));
    }




}
